//
//  MMWebView.m
//  MMWebView
//
//  Created by LEA on 2017/5/22.
//  Copyright © 2017年 LEA. All rights reserved.
//

#import "MMWebView.h"
#import "WKWebView+QWFullScreenPopGesture.h"
#import "TFHpple.h"
#import "HeaderConfig.h"
#import "UMLogFilesManager.h"
@interface MMWebView ()

@property (nonatomic, strong) UIProgressView *progressBar;

@end

@implementation MMWebView

- (instancetype)initWithFrame:(CGRect)frame
{
    
    if (self = [super initWithFrame:frame]) {
        //监听网页加载进度
        [self addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        //监听网页标题变化
        [self addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

#pragma mark - setter
- (void)setDelegate:(id<MMWebViewDelegate>)delegate
{
    _delegate = delegate;
    if (delegate) {
        self.navigationDelegate = self;
    }
}

- (void)setDisplayProgressBar:(BOOL)displayProgressBar
{
    _displayProgressBar = displayProgressBar;
    if (displayProgressBar) {
        _progressBar = [[UIProgressView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, iphone_width, 0.5)];
        _progressBar.backgroundColor = [UIColor clearColor];
        _progressBar.trackTintColor = [UIColor clearColor];
        _progressBar.progressTintColor = [UIColor blackColor];
        
//        CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//            if (@available(iOS 14, *)) {
//                transform = CGAffineTransformMakeScale(1.0f, 0.5f);
//            }
//        _progressBar.transform = transform;
        _progressBar.progress = 0.0;
        [self addSubview:_progressBar];
    }
}

- (void)setTrackTintColor:(UIColor *)trackTintColor
{
    _trackTintColor = trackTintColor;
    if (_progressBar) {
        _progressBar.trackTintColor = trackTintColor;
    }
}

- (void)setProgressTintColor:(UIColor *)progressTintColor
{
    _progressTintColor = progressTintColor;
    if (_progressBar) {
        _progressBar.progressTintColor = progressTintColor;
    }
}

#pragma mark - 进度<KVO>
// 网页加载进度 || 网页标题
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat progress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if ([self.delegate respondsToSelector:@selector(webView:estimatedProgress:)]) {
            [self.delegate webView:self estimatedProgress:progress];
        }
        //如果使用本类中的进度条，代理可不用!!!
//            if (_progressBar) {
//                _progressBar.progress = progress;
//                if (progress == 1.0) {
//                    _progressBar.progress = 0;
//                }
//            }
        [_progressBar setAlpha:1.0f];
        [_progressBar setProgress:self.self.estimatedProgress animated:YES];
        if(self.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [_progressBar setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [_progressBar setProgress:0.0f animated:NO];
            }];
        }
    }
    if (object == self && [keyPath isEqualToString:@"title"])
    {
        NSString *title = [change objectForKey:NSKeyValueChangeNewKey];
        if ([self.delegate respondsToSelector:@selector(webView:didUpdateTitle:)] && title) {
            [self.delegate webView:self didUpdateTitle:title];
        }
    }
}

#pragma mark - 代理<WKNavigationDelegate>
// 网页开始加载
/* 在发送请求之前，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    BOOL isAllow = YES;
    if ([self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        isAllow = [self.delegate webView:self shouldStartLoadWithRequest:navigationAction.request navigationType:navigationAction.navigationType];
    }
    
    
//    decisionHandler(WKNavigationActionPolicyCancel);
    if (isAllow) {
        decisionHandler(WKNavigationActionPolicyAllow);
    } else {
        decisionHandler(WKNavigationActionPolicyCancel);
    }

   
}

/* 在收到响应后，决定是否跳转 */
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//
//    UMLog(@"%@",navigationResponse.response.URL.absoluteString);
//    //允许跳转
////    decisionHandler(WKNavigationResponsePolicyAllow);
//    //不允许跳转
//    decisionHandler(WKNavigationResponsePolicyCancel);
//}

// 网页开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [self.delegate webViewDidStartLoad:self];
    }
}

// 网页完成加载
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    if ([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.delegate webViewDidFinishLoad:self];
    }
    
    if ([self.str containsString:@"保修"]) {
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
    }
    
    NSString *doc =@"document.body.outerHTML";
    [webView evaluateJavaScript:doc completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
        
        if (error) {
            UMLog(@"%@",error);
        }else{
            UMLog(@"html -- : %@",htmlStr);
//            NSData *htmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:htmlStr]];
//            NSData *htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
            NSData *mydata = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
            TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:mydata];
            NSArray *itemArray = [xpathParser searchWithXPathQuery:@"//div[@class = 'tips-box']"];
            //通过for in 在itemArray数组中 循环查找子节点
            for (TFHppleElement *hppleElement in itemArray) {
                
                NSMutableDictionary *ondedic = [hppleElement valueForKey:@"node"];
                NSMutableDictionary *nodeChildArray = [ondedic valueForKey:@"nodeChildArray"];
                NSArray *nodeContentary = [nodeChildArray valueForKey:@"nodeContent"];
                if (nodeContentary.count>0) {
                    NSString *nodeContentStr = [nodeContentary objectAtIndex:0];
                    UMLog(@"%@",nodeContentStr);
                }
                
            /***
            这段被正则表达代替 @"//div[@class = 'cell item']"]
              if ([[hppleElement objectForKey:@"class" ] isEqualToString:@"cell item"]) {
              [self.allDataMutableArray addObject:hppleElement];
              }
            */
            }
            
            
        }
    }];
    
    NSString *JsStr = @"(document.getElementsByTagName(\"video\")[0]).src";
        [webView evaluateJavaScript:JsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            if(![response isEqual:[NSNull null]] && response != nil){
                //截获到视频地址了
                UMLog(@"response == %@",response);
                if (self.mmwebtit) {
                    self.mmwebtit(response);
                }
                
            }else{
                //没有视频链接
            }
        }];
    
    NSString *titStr = @"document.getElementsByName(\"tips-box\"[0])";
    [webView evaluateJavaScript:titStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if(![response isEqual:[NSNull null]] && response != nil){
            //截取到了文本信息
            UMLog(@"response == %@",response);
        }else{
            //没有视频链接
        }
    }];
    
//    NSString *tit2Str = @"document.getElementsByClassName(\"tips-box\")";
//    [webView evaluateJavaScript:tit2Str completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        if(![response isEqual:[NSNull null]] && response != nil){
//            //截取到了文本信息
//            UMLog(@"response == %@",response);
//        }else{
//            //没有视频链接
//        }
//    }];

//        [webView evaluateJavaScript:doc
//
//                         completionHandler:^(id_Nullable htmlStr,NSError * _Nullable error) {
//
//                             if (error) {
//
//                                 UMLog(@"JSError:%@",error);
//
//                             }
//
//                             UMLog(@"html--:%@",htmlStr);
//
//                         }] ;
}

// 网页加载出错
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    if ([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [self.delegate webView:self didFailLoadWithError:error];
    }
}

#pragma mark - dealloc
- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"estimatedProgress"];
    [self removeObserver:self forKeyPath:@"title"];
}


@end


